<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;

class BrankController extends Controller
{
   /**
    * 品牌添加页面
    */
   public function getAdd()
   {
        return view('webadmin.brank.add');
   }

   /**
    * 品牌的插入操作
    */
   public function postInsert(Request $request) 
   {
   	 	//提取参数
      $res = $request -> except(['_token']);
      $branks['name'] = $res['name'];
      
     
      //图片上传
      if($request->hasFile('img')){
          $filename = time().rand(10000,90000);
          $suffix = $request->file('img')->getClientOriginalExtension(); 
          $dirname = './uploads/branks/';
          $file = $filename.'.'.$suffix;
          $request -> file('img') -> move($dirname,$file);
          $branks['img'] = $dirname.$file;
      }
      //执行数据库插入
      $nRes = DB::table('branks')->insert($branks);

        if($nRes) {
            return redirect('/brank/index');
        }else{
            return back();
        }
   }

   /**
    * 品牌的列表显示
    */
   public function getIndex()
   {
   		$res = DB::table('branks') -> get();
   		return view('webadmin.brank.index', [
   			'branks' => $res
   			]);
   }

   /**
    * 品牌的修改界面
    */
   public function getEdit(Request $request)
   {	
   		$id = $request -> input('id');
   		//读取当前分类的信息
        $info = DB::table('branks') -> where('id','=',$id) -> first();
         //解析模板
        return view('webadmin.brank.edit', [
            'info'=>$info
            ]);
   }

   /**
    * 品牌更新操作
    */
   	public function postUpdate(Request $request)
   	{
   		$data = $request->except(['_token', 'id']);
      $branks['name'] = $data['name'];
      //图片上传
      if($request->hasFile('img')){
          $filename = time().rand(10000,90000);
          $suffix = $request->file('img')->getClientOriginalExtension(); 
          $dirname = './uploads/branks/';
          $file = $filename.'.'.$suffix;
          $request -> file('img') -> move($dirname,$file);
          $branks['img'] = $dirname.$file;
      }
   		//更新
        $res = DB::table('branks')->where('id','=', $request->input('id'))->update($branks);
         //判断
        if($res) {
            return redirect('/brank/index')->with('info','更新成功');
        }else {
            return back()->with('info', '更新失败');
        }
   	}

   	/**
   	 * 删除操作
   	 */
	public function getDelete(Request $request)
	{
		//获取id
        $id = $request->input('id');
        //删除当前的品牌
        $res = DB::table('branks')->where('id','=',$id)->delete();
        if($res) {
            return back()->with('info','删除成功');
        }else{
            return back()->with('info','删除失败');
        }
	}

}

